import Cookies from 'js-cookie';
import { request, http, lz } from '@zny/utils';
import { setLocalStorage, getLocalStorage } from '@zny/hooks';
import { Session } from './Session';
import { WebVariable } from './WebVariable';
import { UserInfo } from '../models/UserInfo';

export class AfterLogin {
  // 由于一二级菜单都会进入这个地方鉴权，加isFirst参数作为区分，true 1级，false 二级菜单。
  static checkAuthToken(isFirst: boolean = true): Promise<UserInfo | undefined> {
    const znyToken = JSON.stringify({
      expiresIn: 86400,
      refreshTokenExpiresIn: 604800,
      license: 'powered+by+microservices',
      authority: '',
      permission: '',
      avatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
      accessToken:
        'eyJ0eXAiOiJKc29uV2ViVG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJ1c2VyX2lkIjoiOEE1Qjg4RDYtNkRDNy1FMkY0LTAxNkUtMTA0RTYxQTgwMDNCIiwidG9rZW5fdHlwZSI6ImFjY2Vzc190b2tlbiIsImNsaWVudF9pZCI6InN3b3JkIiwiZXhwIjoxNjA0MDIyMzE1LCJuYmYiOjE2MDM5MzU5MTV9.TxIV9M2RHMqVfTaxURn7FQ1NKOEtN6AQr_Is0wPwTIc',
      tokenType: 'bearer',
      userName: '',
      account: '',
      refreshToken:
        'eyJ0eXAiOiJKc29uV2ViVG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJ1c2VyX2lkIjoiOEE1Qjg4RDYtNkRDNy1FMkY0LTAxNkUtMTA0RTYxQTgwMDNCIiwidG9rZW5fdHlwZSI6InJlZnJlc2hfdG9rZW4iLCJjbGllbnRfaWQiOiJzd29yZCIsImV4cCI6MTYwNDU0MDcxNSwibmJmIjoxNjAzOTM1OTE1fQ.2yafh-7bIpfTsfK03WsvQpHA2eRE0XN0pkBHcJdTCkc',
    });
    const cookie_val = znyToken;
    // const cookie_UserId = Cookies.get('portal_sso');
    const cookie_UserId = '8a5b88d66dc7e2f4016e104e61a8003b';
    let pathname = location.origin;
    let urlPath = '/api/usm/ProjectUser/GetModelById';
    if (process.env.NODE_ENV == 'development') {
      // pathname = "http://10.219.86.03:8001"
      pathname = 'http://10.219.86.138:8001';
    }

    if (cookie_val === undefined || cookie_UserId == undefined) {
      return Promise.resolve(undefined);
    } else {
      const deCodeCookie = decodeURIComponent(cookie_val);
      const obj = JSON.parse(deCodeCookie);

      let userId = (
        cookie_UserId.slice(0, 8) +
        '-' +
        cookie_UserId.slice(8, 12) +
        '-' +
        cookie_UserId.slice(12, 16) +
        '-' +
        cookie_UserId.slice(16, 20) +
        '-' +
        cookie_UserId.slice(20, 32)
      ).toUpperCase();

      const { accessToken } = obj;
      if (!isFirst) {
        const globalSettings = localStorage.getItem('userInfo');
        let projectId = '';
        if (globalSettings) {
          console.log(JSON.parse(lz(globalSettings, true)), '进入二级菜单后获取到的默认配置信息');
          projectId = JSON.parse(lz(globalSettings, true))._LoginProjectId;
        }

        let headers = {
          _LoginProjectId: projectId || '',
          _SysId: WebVariable.sysId,
          _TenantId: WebVariable.tenantId,
          token: accessToken,
          Authorization: accessToken,
        };

        request.extendOptions({
          headers,
        });
        http.extendOptions({
          headers,
        });

        urlPath = '/api/usm/ProjectUser/GetModelById';
      } else {
        console.log('进入一级菜单');
        let headers = {
          _LoginProjectId: '',
          _SysId: WebVariable.sysId,
          _TenantId: WebVariable.tenantId,
          token: accessToken,
          Authorization: accessToken,
        };

        request.extendOptions({
          headers,
        });
        http.extendOptions({
          headers,
        });

        urlPath = '/api/usm/SysUser/GetModelById';
      }

      return new Promise((resolve, reject) => {
        request(`${urlPath}?id=${userId}`)
          .then(data => {
            if (data) {
              data.value = { accessToken: obj.accessToken };
              console.log(data, '获取到的用户信息......');
              const currentUser = Session.getUser();
              Session.setUser(
                data,
                currentUser?._LoginProjectId ?? '',
                currentUser?._TenantId ?? '',
                currentUser?.projectName ?? '',
              );
              // 进入一级菜单时，清空projectId
              let defaultSettings = getLocalStorage('globalSettings');
              defaultSettings._LoginProjectId = '';
              setLocalStorage('globalSettings', defaultSettings);
              setLocalStorage('globalStore', { ...data, departmentId: data.orgId });
              resolve(data);
            }
          })
          .catch(error => {
            console.log(error, 'error');
            reject();
            setTimeout(() => {
              Session.logout();
            }, 3000);
          });
      });
    }
  }
}
